package org.amphiprion.descentv2assistant.adapter;

import java.util.HashMap;
import java.util.List;

import org.amphiprion.descentv2assistant.App;
import org.amphiprion.descentv2assistant.ApplicationConstants;
import org.amphiprion.descentv2assistant.R;
import org.amphiprion.descentv2assistant.entity.Ability;
import org.amphiprion.descentv2assistant.entity.Monster;
import org.amphiprion.descentv2assistant.ui.views.PinnedHeaderListView;
import org.amphiprion.descentv2assistant.ui.views.PinnedHeaderListView.PinnedHeaderAdapter;

import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SectionIndexer;
import android.widget.TextView;

public class MonsterListAdapter extends BaseAdapter implements PinnedHeaderListView.PinnedHeaderAdapter, SectionIndexer, AbsListView.OnScrollListener {
	public static final int SMALL = 2;
	protected FragmentActivity mContext;
	private MonsterIndexer mIndexer;
	protected LayoutInflater mInflater;
	protected List<Monster> mItems;
	private int mMode;
	private HashMap<String, Integer> mMonsterCountMap;

	public MonsterListAdapter(FragmentActivity paramFragmentActivity, List<Monster> monsters) {
		this.mContext = paramFragmentActivity;
		this.mInflater = LayoutInflater.from(paramFragmentActivity);
		this.mItems = monsters;
		initItems();
	}

	private String getSectionName(Monster m) {
		// String s = null;
		// if (m.isMajor()) {
		// s = mContext.getResources().getString(R.string.act_major_header);
		// } else {
		// s = mContext.getResources().getString(R.string.act_minor_header);
		// }
		// s = MessageFormat.format(s, "" + m.getAct());
		// return s;
		return mIndexer.getSectionName(m);
	}

	private void bindSectionHeader(View paramView, int monsterIndex) {
		Monster monster = this.mItems.get(monsterIndex);

		View headerView = paramView.findViewById(R.id.header);
		ImageView img = (ImageView) paramView.findViewById(R.id.header_image);
		// App.setImage(img, monster.getArchetype());

		TextView sectionTitle = (TextView) paramView.findViewById(R.id.header_text);
		TextView numberOfEpisodeInSection = (TextView) paramView.findViewById(R.id.totalCount);
		View headerDividerView = paramView.findViewById(R.id.divider);

		// Check box for watched
		// initSeasonTicker(episode, paramView, true);

		// Check if we need to display the header

		int i = getSectionForPosition(monsterIndex);
		Object[] arrayOfObject;
		if (getPositionForSection(i) == monsterIndex) {
			arrayOfObject = getSections();
			try {
				sectionTitle.setText((String) arrayOfObject[i]);
				headerView.setVisibility(0);
				numberOfEpisodeInSection.setText(String.valueOf(getMonsterCount(getSectionName(monster))));
				headerDividerView.setVisibility(0);
				// if (-1 + getPositionForSection(i + 1) == episodeIndex) {
				// headerView.setVisibility(8);
				// headerDividerView.setVisibility(8);
				// }
				return;
			} catch (Exception ex) {
				Log.e(ApplicationConstants.PACKAGE, "", ex);
			}
		} else {
			headerView.setVisibility(8);
			headerDividerView.setVisibility(8);
		}
	}

	private int getMonsterCount(String sectionName) {
		return this.mMonsterCountMap.get(sectionName).intValue();
	}

	private void inflateView(View view, final int index, ViewHolder paramViewHolder) {
		final Monster localMonster = getItem(index);

		paramViewHolder.mName.setText(localMonster.getName());
		if (localMonster.isMajor()) {
			paramViewHolder.mName.setTextColor(mContext.getResources().getColor(R.color.default_red));
		} else {
			paramViewHolder.mName.setTextColor(mContext.getResources().getColor(R.color.default_blue));
		}

		paramViewHolder.mCharacSpeed.setText("" + localMonster.getCharacteristic().getSpeed());
		paramViewHolder.mCharacHealth.setText("" + localMonster.getCharacteristic().getHealth());

		// defense
		paramViewHolder.mCharacDefense.removeAllViews();
		String[] dice = localMonster.getCharacteristic().getDefense().split(",");
		for (String die : dice) {
			int nb = 1;
			try {
				nb = Integer.parseInt(die.substring(0, 1));
			} catch (Throwable e) {
			}
			for (int i = 0; i < nb; i++) {
				ImageView img = (ImageView) this.mInflater.inflate(R.layout.image_dice, null);
				String name = die.substring(1);
				App.setImage(img, "/images/DiceDefense/", name);
				paramViewHolder.mCharacDefense.addView(img);
			}
		}

		// attack
		paramViewHolder.mCharacAttack.removeAllViews();
		dice = localMonster.getAttack().getDice().split(",");
		for (String die : dice) {
			if ("".equals(die)) {
				continue;
			}
			int nb = 1;
			try {
				nb = Integer.parseInt(die.substring(0, 1));
			} catch (Throwable e) {
			}
			for (int i = 0; i < nb; i++) {
				ImageView img = (ImageView) this.mInflater.inflate(R.layout.image_dice, null);
				String name = die.substring(1);
				App.setImage(img, "/images/DiceAttack/", name);
				paramViewHolder.mCharacAttack.addView(img);
			}
		}

		App.setImage(paramViewHolder.mScreencap, localMonster, mContext.getSupportFragmentManager());

		// abilities
		// LinearLayout rowL = null;
		for (int i = 0; i < 4; i++) {
			paramViewHolder.abilityIcons[i].setVisibility(View.GONE);
			paramViewHolder.abilityTexts[i].setVisibility(View.GONE);
		}
		int colIndex = 0;
		for (Ability ab : localMonster.getAbilities()) {

			ImageView img = paramViewHolder.abilityIcons[colIndex];
			if (ab.isAction()) {
				img.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ic_action));
				img.setVisibility(View.VISIBLE);
			} else if (ab.isFlash()) {
				img.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ic_flash));
				img.setVisibility(View.VISIBLE);
			} else {
				img.setVisibility(View.GONE);
			}

			TextView tv = paramViewHolder.abilityTexts[colIndex];
			tv.setText(ab.getName());
			tv.setVisibility(View.VISIBLE);
			colIndex++;
			if (colIndex == 4) {
				break;
			}
		}

		bindSectionHeader(view, index);

	}

	private void initItems() {
		this.mIndexer = new MonsterIndexer(this.mContext, this.mItems);
		this.mMonsterCountMap = new HashMap();
		for (int i = 0; i < this.mItems.size(); i++) {
			String sectionName = getSectionName(this.mItems.get(i));
			Integer localInteger = this.mMonsterCountMap.get(sectionName);
			if (localInteger == null) {
				this.mMonsterCountMap.put(sectionName, Integer.valueOf(1));

			} else {
				this.mMonsterCountMap.put(sectionName, Integer.valueOf(1 + localInteger.intValue()));
			}

			// if (this.mSeasonWatchMap.get(Integer.valueOf(seasonId)) != null) {
			// if ((this.mSeasonWatchMap.get(Integer.valueOf(seasonId)).booleanValue())) {
			// this.mSeasonWatchMap.put(Integer.valueOf(seasonId), Boolean.valueOf(this.mItems.get(i).isWatched()));
			// }
			// } else {
			// this.mSeasonWatchMap.put(Integer.valueOf(seasonId), Boolean.valueOf(this.mItems.get(i).isWatched()));
			// }
		}
	}

	// private void initSeasonTicker(final Episode paramEpisode, View paramView, boolean paramBoolean) {
	// ImageView localImageView = (ImageView) paramView.findViewById(R.id.watch_season);
	// int i = paramEpisode.getSeasonId();
	// Boolean seasonWatched = this.mSeasonWatchMap.get(Integer.valueOf(i));
	// if (!seasonWatched.booleanValue()) {
	// localImageView.setImageResource(R.drawable.ic_watched_grey);
	// // localImageView.setBackgroundResource(R.drawable.holo_selector);
	// localImageView.setOnClickListener(new View.OnClickListener() {
	// @Override
	// public void onClick(View paramAnonymousView) {
	// EpisodeDiffusionListAdapter.this.tickEpisode(paramEpisode, true);
	// }
	// });
	// return;
	// } else {
	// localImageView.setImageResource(R.drawable.ic_watched_blue);
	// // if (!paramBoolean) {
	// // localImageView.setImageResource(R.drawable.ic_watched_blue);
	// // localImageView.setBackgroundResource(R.drawable.holo_selector);
	// // } else {
	// // localImageView.setImageResource(R.drawable.green_tick_selector);
	// // localImageView.setBackgroundResource(R.drawable.green_selector);
	// // }
	// localImageView.setOnClickListener(new View.OnClickListener() {
	// @Override
	// public void onClick(View paramAnonymousView) {
	// EpisodeDiffusionListAdapter.this.tickEpisode(paramEpisode, false);
	// }
	// });
	// }
	//
	// }

	private void setMonster(int index, Monster monster) {
		this.mItems.set(index, monster);
		initItems();
		notifyDataSetChanged();
	}

	// private void tickEpisode(Episode paramEpisode, boolean watched) {
	// if (this.mSeasonWatchListener != null) {
	// int serieId = paramEpisode.getSerieId();
	// String seasonId = "" + paramEpisode.getSeasonId();
	// this.mSeasonWatchListener.onSeasonWatch(serieId, seasonId, watched);
	// }
	// }

	@Override
	public void configurePinnedHeader(View view, int index, int paramInt2) {
		Monster localMonster = this.mItems.get(index);
		ImageView img = (ImageView) view.findViewById(R.id.header_image);
		// App.setImage(img, localMonster.getArchetype());
		TextView localTextView1 = (TextView) view.findViewById(R.id.header_text);
		TextView localTextView2 = (TextView) view.findViewById(R.id.totalCount);
		// initSeasonTicker(localEpisode, paramView, false);
		int i = getSectionForPosition(index);

		localTextView2.setText(String.valueOf(getMonsterCount(getSectionName(localMonster))));
		String sectionTitle = (String) this.mIndexer.getSections()[i];
		int j = App.dpiToPixels(mContext, 8);
		localTextView1.setPadding(j, j, j, j);
		localTextView1.setText(sectionTitle);
		view.setVisibility(0);
		return;

	}

	@Override
	public int getCount() {
		if (this.mItems != null) {
			return this.mItems.size();
		} else {
			return 0;
		}
	}

	@Override
	public Monster getItem(int paramInt) {
		return this.mItems.get(paramInt);
	}

	@Override
	public long getItemId(int paramInt) {
		return paramInt;
	}

	@Override
	public int getPinnedHeaderState(int position) {
		int i = PinnedHeaderAdapter.PINNED_HEADER_GONE;
		if ((this.mIndexer == null) || (getCount() == 0)) {

		} else {
			if (position >= 0) {

				int j = getPositionForSection(1 + getSectionForPosition(position));
				if ((j != -1) && (position == j - 1)) {
					i = PinnedHeaderAdapter.PINNED_HEADER_PUSHED_UP;
				} else {
					i = PinnedHeaderAdapter.PINNED_HEADER_VISIBLE;
				}
			}
		}
		return i;
	}

	@Override
	public int getPositionForSection(int paramInt) {
		try {
			return this.mIndexer.getPositionForSection(paramInt);
		} catch (Exception localException) {
			return 0;
		}
	}

	@Override
	public int getSectionForPosition(int paramInt) {
		try {
			int i = this.mIndexer.getSectionForPosition(paramInt);
			return i;
		} catch (Exception localException) {
			int i = 0;
			return i;
		}
	}

	@Override
	public Object[] getSections() {
		return this.mIndexer.getSections();
	}

	@Override
	public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
		ViewHolder localViewHolder;
		int i;
		if (paramView == null) {
			localViewHolder = new ViewHolder();
			LayoutInflater localLayoutInflater = this.mInflater;
			// if (this.mMode == SMALL) {
			i = R.layout.list_item_monster;
			// } else {
			// i = R.layout.list_item_episode;
			// }
			paramView = localLayoutInflater.inflate(i, null);
			localViewHolder.mName = ((TextView) paramView.findViewById(R.id.monsterName));

			localViewHolder.mCharacSpeed = ((TextView) paramView.findViewById(R.id.monsterMove));
			localViewHolder.mCharacHealth = ((TextView) paramView.findViewById(R.id.monsterHealth));
			localViewHolder.mCharacDefense = ((LinearLayout) paramView.findViewById(R.id.monsterDefense));
			localViewHolder.mCharacAttack = ((LinearLayout) paramView.findViewById(R.id.monsterAttack));
			// localViewHolder.mGridLayout = ((LinearLayout) paramView.findViewById(R.id.grid_abilities));

			localViewHolder.abilityIcons[0] = (ImageView) paramView.findViewById(R.id.ability_icon1);
			localViewHolder.abilityIcons[1] = (ImageView) paramView.findViewById(R.id.ability_icon2);
			localViewHolder.abilityIcons[2] = (ImageView) paramView.findViewById(R.id.ability_icon3);
			localViewHolder.abilityIcons[3] = (ImageView) paramView.findViewById(R.id.ability_icon4);

			localViewHolder.abilityTexts[0] = (TextView) paramView.findViewById(R.id.ability_text1);
			localViewHolder.abilityTexts[1] = (TextView) paramView.findViewById(R.id.ability_text2);
			localViewHolder.abilityTexts[2] = (TextView) paramView.findViewById(R.id.ability_text3);
			localViewHolder.abilityTexts[3] = (TextView) paramView.findViewById(R.id.ability_text4);

			localViewHolder.mScreencap = ((ImageView) paramView.findViewById(R.id.screenCap));

			paramView.setTag(localViewHolder);
		} else {
			localViewHolder = (ViewHolder) paramView.getTag();
		}

		inflateView(paramView, paramInt, localViewHolder);
		return paramView;
	}

	@Override
	public void onScroll(AbsListView paramAbsListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		if (((paramAbsListView instanceof PinnedHeaderListView))) {
			((PinnedHeaderListView) paramAbsListView).configureHeaderView(firstVisibleItem);
		}
	}

	@Override
	public void onScrollStateChanged(AbsListView paramAbsListView, int scrollState) {

	}

	public void setItems(List<Monster> monsters) {
		this.mItems = monsters;
		initItems();
		notifyDataSetChanged();
	}

	public void setMode(int paramInt) {
		this.mMode = paramInt;
	}

	// public void setOnSeasonWatch(OnWatchSeasonListener paramOnWatchSeasonListener) {
	// this.mSeasonWatchListener = paramOnWatchSeasonListener;
	// }

	class ViewHolder {
		TextView mName;

		TextView mCharacSpeed;
		TextView mCharacHealth;
		LinearLayout mCharacDefense;
		LinearLayout mCharacAttack;

		ImageView[] abilityIcons = new ImageView[4];
		TextView[] abilityTexts = new TextView[4];

		// LinearLayout mGridLayout;
		public ImageView mScreencap;

		ViewHolder() {
		}
	}

	// public static abstract interface OnWatchSeasonListener {
	// public abstract void onSeasonWatch(int serieId, String seasonId, boolean watched);
	// }
}